package cn.dapeng.rpc.common.serial;

import cn.dapeng.rpc.common.RpcRequest;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class KryoSerializerCoder {

    private static ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    public synchronized static byte[] serial(Object object) throws Exception {
        byteArrayOutputStream.reset();
        try (Output output = new Output(byteArrayOutputStream)) {
            new Kryo().writeObject(output, object);
            output.close();
            return byteArrayOutputStream.toByteArray();
        }
    }

    public synchronized static <T> T deseria(byte[] bytes, Class<T> clazz) throws Exception {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); Input input = new Input(bais)) {
            return new Kryo().readObject(input, clazz);
        }
    }

    public static void main(String[] args) throws Exception {
        RpcRequest request = new RpcRequest(22222222222L, "m", "x", new Class[] {String.class}, null);

        byte[] b = serial(request);
        RpcRequest r = deseria(b, RpcRequest.class);

        System.out.println(r);
    }

}
